const pool = require('../config/db')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const { JWT_SECRET } = require('../config/constants')

// 生成JWT token
const generateToken = (user) => {
  return jwt.sign(
    { 
      id: user.id,
      username: user.username,
      isAdmin: user.is_admin 
    },
    JWT_SECRET,
    { expiresIn: '24h' }
  )
}

const userController = {
  // 用户注册
  async register(req, res) {
    try {
      const { username, password, phone, is_admin, village_id } = req.body
      console.log(req.body);
      
      // 检查用户名是否已存在
      const [existingUsers] = await pool.execute(
        'SELECT * FROM users WHERE username = ?',
        [username]
      )
      
      if (existingUsers.length > 0) {
        return res.status(400).json({
          success: false,
          message: '用户名已被注册'
        })
      }
      console.log(village_id);
      
      const finalVillageId = village_id === undefined ? null : village_id;
      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10)

      // 创建新用户
      const [result] = await pool.execute(
        'INSERT INTO users (username, password, phone, is_admin,village_id) VALUES (?, ?, ?, ?, ?)',
        [username, hashedPassword, phone, is_admin ? 1 : 0,finalVillageId]
      )
      res.status(201).json({
        success: true,
        message: '注册成功'
      })
    } catch (error) {
      console.error('注册错误:', error)
      res.status(500).json({
        success: false,
        message: '注册失败',
        error: error.message
      })
    }
  },

  // 用户登录
  async login(req, res) {
    try {
      const { username, password } = req.body
      console.log('Login attempt:', { username, password })

      // 查找用户
      const [users] = await pool.execute(
        'SELECT * FROM users Where username = ?',
        [username]
      )
      console.log('Found users:', users)

      if (users.length === 0) {
        console.log('User not found')
        return res.status(401).json({
          success: false,
          message: '用户名或密码错误'
        })
      }

      const user = users[0]
      console.log('Comparing passwords:', { 
        provided: password,
        stored: user.password
      })

      // 验证密码
      const isMatch = await bcrypt.compare(password, user.password)
      console.log('Password match:', isMatch)
      
      if (!isMatch) {
        console.log('Password mismatch')
        return res.status(401).json({
          success: false,
          message: '用户名或密码错误'
        })
      }

      // 生成token
      const token = generateToken(user)

      res.status(201).json({
        success: true,
        message: '登录成功',
        data: {
          token,
          userInfo: {
            id: user.id,
            username: user.username,
            phone: user.phone,
            isAdmin: user.is_admin
          }
        }
      })
      
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '登录失败',
        error: error.message
      })
    }
  },

  // 获取用户信息
  async getUserInfo(req, res) {
    try {
      const [users] = await pool.execute(
        'SELECT * FROM users WHERE id = ?',
        [req.user.id]
      )

      if (users.length === 0) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        })
      }

      res.json({
        success: true,
        data: users[0]
      })
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '获取用户信息失败',
        error: error.message
      })
    }
  },

  // 重置用户密码
  async resetPassword(req, res) {
    try {
      const { username } = req.body
      const password = '123456' // 默认密码

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10)

      // 更新用户密码
      const [result] = await pool.execute(
        'UPDATE users SET password = ? WHERE username = ?',
        [hashedPassword, username]
      )

      if (result.affectedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        })
      }

      res.json({
        success: true,
        message: '密码重置成功'
      })
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '密码重置失败',
        error: error.message
      })
    }
  }
}

module.exports = userController 